/**
 * @file ldavg.c
 * Load average source for TrayInfo.
 */

/* Load average support added by Laszlo Ashin <kodest@gmail.com> */

#include <stdio.h>

#include "trayinfo.h"

/** Source handle. */
static source_handle_t *ldavg_sh;

static int
ldavg_write(/*@unused@*/ double now, /*@unused@*/ int fd)
{
	float ld[3];
	int i;
	FILE *f = fopen("/proc/loadavg", "r");
	if (!f) return 0;
	i = fscanf(f, "%f %f %f", ld, ld + 1, ld + 2);
	(void)fclose(f);
	if (i != 3) return 0;

	return show("%.2f %.2f %.2f", ld[0], ld[1], ld[2]);
}

int
init_module(module_phase_t phase)
{
	switch (phase) {
	case MODULE_PHASE_INIT: {
		source_t source = {
			.name = "ldavg",
			.write = ldavg_write,
		};
		ldavg_sh = register_source(&source);
		return (ldavg_sh == NULL);
	}
	case MODULE_PHASE_EXIT:
		return forget_source(ldavg_sh);
	}
}
